package cn.tedu.charging.order.config;

import cn.tedu.charging.order.mqtt.MqttClientCallback;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

@Configuration
@Slf4j
public class MqttClientConfiguration {
    //将yaml中的自定义属性注入到配置类 未了创建容器bean对象MqttClient赋值使用
    @Value("${charging.emqx.address}")
    private String address;
    @Value("${charging.emqx.username}")
    private String username;
    @Value("${charging.emqx.password}")
    private String password;
    @Autowired
    private MqttClientCallback mqttClientCallback;
    //准备一个@Bean方法 将底层MqttClient创建成容器bean对象,才能在项目中使用
    @Bean
    public MqttClient mqttClient(){
        //一般这种jar包资源中的底层连接对象都有3种创建方式
        //1.工厂factory模式
        //2.构建器builder模式
        //3.直接new 调用setter赋值
        MqttClient mqttClient = null;
        try{
            //1.先new一个对象 调用构造方法传递必要参数 address(emqx服务端地址) clientId(每个客户端唯一编码,保证唯一) persistence(持久化方式)
            mqttClient=new MqttClient(address, UUID.randomUUID().toString(),new MemoryPersistence());
            //2.要给连接对象提供必要的参数选项,比如username password 选项options对象可以影响客户端连接的一些功能和特性
            MqttConnectOptions options=new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            //添加连接的回调函数
            mqttClient.setCallback(mqttClientCallback);
            //3.创建连接
            mqttClient.connect();
            //让连接建立成功后 监听订阅主题 让程序根据需求订阅不同的主题
            /*mqttClient.subscribe("topic01");
            mqttClient.subscribe("$share/order/topic02");*/
            //业务主题 charging/device/check/result
            mqttClient.subscribe("$share/order/charging/device/check/result");
            mqttClient.subscribe("$share/order/charging/device/progress");
        }catch (Exception e){
            log.error("创建MqttClient对象失败");
        }
        return mqttClient;
    }
}
